<script setup lang="ts">
import {ref, onMounted} from 'vue'
import {Dayjs} from 'dayjs';
import {SearchOutlined, UndoOutlined, EditOutlined, ClockCircleOutlined} from '@ant-design/icons-vue';
import type {SelectProps} from 'ant-design-vue';

import Processing from '@components/Processing'

type SearchForm = {
  key: null | string,
  status: null | number,
  start_at: null | number,
  end_at: null | number,
  sort?: {
    order: null | string,
    columnKey: null | string
  } | null,
}
//日期选择器
const searchOrderPicker = ref<Dayjs[]>([])
//状态
const statusOptions = ref<SelectProps['options']>([
  {
    label: '待办',
    value: 0,
  }, {
    label: '办理中',
    value: 1,
  }
])
//查询条件
const searchForm = ref<SearchForm>({
  key: null,
  status: null,
  start_at: null,
  end_at: null,
})
//数据
const pagination = ref({
  page: 1,
  pageSize: 15,
  pageSizeOptions: ['15', '20', '30', '40', '50'],
  total: 0,
})
//办理模态框
const processingModal = ref<boolean>(false);
const processingData = ref<Object>({})
//当前页数据
const dataLoading = ref<boolean>(false);
const columns = ref([
  {
    title: 'No.',
    dataIndex: 'index',
    width: 60,
    align: 'center',
  },
  {
    title: '订单号',
    dataIndex: 'order_sn',
    width: 220,
  },
  {
    title: '真实姓名',
    dataIndex: 'name',
  },
  {
    title: '电话',
    dataIndex: 'phone',
    width: 170,
  },
  {
    title: '微信',
    dataIndex: 'user',
    width: 170,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'create_at',
    width: 170,
    sorter: {
      compare: (a: any, b: any) => a.create_at - b.create_at,
      multiple: 3,
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 70,
    align: 'center',
  },
])
const dataList = ref<any[]>([])
//选择日期
const changeDatePicker = (dates: [Dayjs, Dayjs]) => {
  searchForm.value.start_at = dates ? dates[0].unix() : null;
  searchForm.value.end_at = dates ? dates[1].unix() : null;
}
//切换页码
const changePage = (page: number, pageSize: number) => {
  pagination.value.page = page;
  pagination.value.pageSize = pageSize;
  getDataList()
}
//查询
const getDataList = () => {
  dataLoading.value = true;
  dataList.value = []; // 确保每次查询时清空数据列表

  for (let i = 0; i < pagination.value.pageSize; i++) {
    const order_sn = `ORD${Math.floor(Math.random() * 1000000)}`; // 生成随机订单号
    const phone = `138${Math.floor(Math.random() * 100000000)}`; // 生成随机手机号码，假设以 138 开头

    // 随机生成创建时间
    const createDate = new Date(Date.now() - Math.floor(Math.random() * 10000000000));
    const create_at = formatDate(createDate); // 格式化创建时间

    // 随机生成处理时间，有可能为空
    const processingDate = Math.random() > 0.5 ? new Date(Date.now() - Math.floor(Math.random() * 10000000000)) : null;
    const processing_at = processingDate ? formatDate(processingDate) : ''; // 格式化处理时间
    // 随机生成 status，值为 0 或 1
    const status = Math.random() > 0.5 ? 1 : 0;
    dataList.value.push({
      order_sn: order_sn,
      name: `Edward ${i}`,
      phone: phone,
      create_at: create_at,
      status: status,
      processing_at: processing_at,
    });
  }
  console.log(searchForm.value)
  pagination.value.total = 100;
  dataLoading.value = false;
}
//办理
const processingOrder = (record: any) => {
  processingData.value = record;
  processingModal.value = true;
}
// 格式化日期为 YYYY-MM-DD HH:mm:ss
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 排序
const handleTableChange = (_pagination: any, _filters: any, sorter: any) => {
  searchForm.value.sort = null;
  if (sorter.order) {
    // 处理单个排序
    searchForm.value.sort = {
      order: sorter.order,
      columnKey: sorter.field,
    };
  }
  getDataList();
}
onMounted(() => {
  getDataList()
})

</script>
<template>
  <a-card>
    <a-form
        layout="inline"
        :model="searchForm"
        @keyup.enter="getDataList">
      <a-form-item label="关键字">
        <a-input v-model:value="searchForm.key" style="width: 260px" placeholder="输入订单号、姓名或电话号查询..."
                 allow-clear/>
      </a-form-item>
      <a-form-item label="日期">
        <a-range-picker v-model:value="searchOrderPicker" @change="changeDatePicker"/>
      </a-form-item>
      <a-form-item label="状态">
        <a-select v-model:value="searchForm.status" :options="statusOptions" style="width: 120px"
                  placeholder="请选择状态" allow-clear/>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="getDataList">
            <template #icon>
              <SearchOutlined :style="{fontSize: '16px',position: 'relative',top:'-2px'}"/>
            </template>
            查询
          </a-button>
          <a-button
              @click="()=>{searchForm.key=null;searchForm.start_at=null;searchForm.end_at=null;searchOrderPicker=[];searchForm.status=null}">
            <template #icon>
              <UndoOutlined :style="{fontSize: '16px',position: 'relative',top:'-2px'}"/>
            </template>
            重置
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <div style="margin-top: 20px">
      <a-table :columns="columns" :data-source="dataList"
               :loading="dataLoading"
               :pagination="false"
               @change="handleTableChange"
               size="small" bordered :scroll="{y: 700}">
        <template #bodyCell="{ column, record,index }">
          <template v-if="column.dataIndex === 'index'">
            {{ (index + 1) + (pagination.page - 1) * pagination.pageSize }}
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="record.status?'success':'warning'">
              <template #icon>
                <EditOutlined v-if="record.status"/>
                <clock-circle-outlined v-else/>
              </template>
              {{ record.status ? '办理中' : '待办' }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <a-space>
              <a-button type="link" size="small" @click="processingOrder(record)">办理</a-button>
            </a-space>
          </template>
        </template>
        <template #emptyText>
          <a-empty>
            <template #description>
              暂无相关数据
            </template>
          </a-empty>
        </template>
      </a-table>
      <div style="margin-top: 10px; display: flex; justify-content: end;">
        <a-pagination
            size="small"
            v-model:current="pagination.page"
            v-model:pageSize="pagination.pageSize"
            :page-size-options="pagination.pageSizeOptions"
            show-size-changer
            show-quick-jumper
            :total="pagination.total"
            @change="changePage"
            :show-total="(total: number) => `共 ${total} 条`">
          <template #buildOptionText="props">
            <span>{{ props.value }}条/页</span>
          </template>
        </a-pagination>
      </div>
    </div>
  </a-card>
  <processing v-model:open="processingModal" :order-data="processingData"/>
</template>

<style scoped lang="scss">

</style>